<template>
  <div style="max-width: 500px; margin: 0 auto;">
    <h2>修改密码</h2>
    <el-form :model="form" label-width="80px">
      <el-form-item label="旧密码">
        <el-input v-model="form.password" type="password" placeholder="请输入旧密码" />
      </el-form-item>
      <el-form-item label="新密码">
        <el-input v-model="form.newPassword" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="再次确认">
        <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入新密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitPassword">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const stuId = localStorage.getItem('loginId')
const form = ref({
  password: '',
  newPassword: '',
  confirmPassword: ''
})

const submitPassword = async () => {
  if (!form.value.password || !form.value.newPassword || !form.value.confirmPassword) {
    ElMessage.error('请输入完整信息')
    return
  }
  if (form.value.newPassword !== form.value.confirmPassword) {
    ElMessage.error('两次输入的新密码不一致')
    return
  }
  try {
    const res = await axios.put(
      `http://localhost:8080/student/${form.value.password}/${form.value.newPassword}/editPassword`,
      {
        "id": Number(stuId)
      }
    )
    console.log('修改密码返回：', res.data)
    if (res.data && res.data.code === 200) {
      ElMessage.success('密码修改成功')
      resetForm()
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '修改失败')
    }
  } catch (e) {
    ElMessage.error('修改失败')
  }
}

const resetForm = () => {
  form.value.password = ''
  form.value.newPassword = ''
  form.value.confirmPassword = ''
}
</script>